package com.jasmine.bjstkserver.manager.ip;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.jasmine.bjstkserver.manager.weather.WeatherManager;
import com.jasmine.core.constants.BjsConstants;
import com.jasmine.core.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jasmineXz
 */
@Component
public class IpManager {
    private static final Logger log = LoggerFactory.getLogger(WeatherManager.class);

    private static final String IP_QUERY_URL_WY126 = "http://ip.ws.126.net/ipquery";

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询IP归属,缓存7天
     * @param ip ip
     * @return 归属
     */
    public IpDTO query(String ip) {
        IpDTO ipDTO = JsonUtil.json2Object((String) redisTemplate.opsForValue().get(BjsConstants.Redis.IP_COLLECT + ip),IpDTO.class);

        if (ipDTO != null)
            return ipDTO;

        Map<String,Object> param = new HashMap<>(1);
        param.put("ip",StrUtil.trim(ip));
        HttpResponse now = HttpRequest.get(IP_QUERY_URL_WY126).form(param).execute();
        String jsonStr = StrUtil.sub(now.body(),StrUtil.indexOf(now.body(), '{'),now.body().length());

        log.info("[BJSTK] ip:{}, body:{}",ip,jsonStr);
        try {
            ipDTO = JSONUtil.toBean(jsonStr, IpDTO.class);
            if (ipDTO != null) {
                redisTemplate.opsForValue().set(
                        BjsConstants.Redis.IP_COLLECT + ip,
                        JsonUtil.obj2Json(ipDTO),
                        BjsConstants.Redis.TIME_7_DAY,
                        BjsConstants.Redis.REDIS_SECONDS);
                return ipDTO;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[BJSTK] 解析IPJSON错误, IP:[{}], 错误:[{}]",ip,jsonStr);
        }
        return null;
    }

    public static void main(String[] args) {
        IpManager ipManager = new IpManager();
        ipManager.query("");
    }


}
